package org.repo.ant.registry;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class RepoRegistry {

	private static RepoRegistry _instance;
	private Map<String, File> repos = new HashMap<String, File>();
	
	private File repoBaseDir = null;
	private String REPO_BASE_DIR_NAME = ".repo-ant";
	
	protected RepoRegistry(){}	
	
	public synchronized static RepoRegistry get(){
		if(_instance==null){
			_instance = new RepoRegistry();			
		}
		return _instance;
	}
	
	public void setRepo(String repoName, String repoBase){
		
		if(repoName==null){
			return;
		}
		
		if(repoBase!=null){
			repoBaseDir = new File(repoBase);
		}
		else{
			repoBaseDir = findRepoBaseDir();
		}
		
		if(!repoBaseDir.exists()){
			repoBaseDir.mkdirs();
		}
		
		System.out.println("Using repo base: " + repoBaseDir.getAbsolutePath());
		
		File repoDir = new File(repoBaseDir, repoName);
		if(!repoDir.exists()){
			repoDir.mkdirs();
		}
		repos.put(repoName, repoDir);
	}
	
	public File getRepoPath(String repoName, String repoDirectory){
		if(repoName!=null){
			return repos.get(repoName);
		}
		else{
			File repoDir = new File(repoDirectory);
			if(!repoDir.exists()){
				repoDir.mkdirs();
			}
			return repoDir;
		}		
	}
	
	
	private File findRepoBaseDir(){
		String home = System.getenv("HOMEPATH");
		File homeDir;
		try{
			homeDir = new File(home);
			if(homeDir.exists() && homeDir.isDirectory()){
				File repoBaseDir = new File(homeDir, REPO_BASE_DIR_NAME);
				return repoBaseDir;
			}
		}
		catch(Throwable t){			
		}
		
		home = System.getProperty("user.home");
		try{
			homeDir = new File(home);
			if(homeDir.exists() && homeDir.isDirectory()){
				File repoBaseDir = new File(homeDir, REPO_BASE_DIR_NAME);
				return repoBaseDir;
			}
		}
		catch(Throwable t){			
		}
		
		home = System.getProperty("user.dir");
		try{
			homeDir = new File(home);
			if(homeDir.exists() && homeDir.isDirectory()){
				File repoBaseDir = new File(homeDir, REPO_BASE_DIR_NAME);
				return repoBaseDir;
			}
		}
		catch(Throwable t){			
		}
		
		return null;
		
	}
	
}
